"""
STS令牌模块
实现令牌生成、验证和格式化功能
"""

import time
from typing import Optional, Tuple
from .crypto import STSCrypto


class STSToken:
    """STS令牌类"""
    
    def __init__(self, crypto: Optional[STSCrypto] = None):
        """
        初始化令牌模块
        
        Args:
            crypto: 加密模块实例，如果为None则创建新的实例
        """
        self.crypto = crypto or STSCrypto()
    
    def generate_token(self, meter_id: str, amount: int, 
                      transfer_counter: int) -> str:
        """
        生成STS令牌
        
        Args:
            meter_id: 表计ID
            amount: 充值金额（以分为单位）
            transfer_counter: 传输计数器
            
        Returns:
            格式化的令牌字符串
        """
        # 构建令牌数据
        token_data = self._build_token_data(meter_id, amount, transfer_counter)
        
        # 计算CRC
        crc = self.crypto.calculate_crc16(token_data)
        
        # 加密令牌数据
        encrypted_data = self.crypto.encrypt_token_data(
            meter_id, amount, transfer_counter, crc
        )
        
        # 转换为十六进制字符串
        token_hex = encrypted_data.hex().upper()
        
        # 格式化为标准STS令牌格式（每4个字符一组）
        formatted_token = ' '.join([token_hex[i:i+4] for i in range(0, len(token_hex), 4)])
        
        return formatted_token
    
    def verify_token(self, token: str, meter_id: str) -> Tuple[bool, Optional[dict]]:
        """
        验证STS令牌
        
        Args:
            token: 令牌字符串
            meter_id: 表计ID
            
        Returns:
            (验证是否通过, 令牌数据字典)
        """
        try:
            # 清理令牌格式
            clean_token = token.replace(' ', '').replace('-', '')
            
            # 转换为字节
            encrypted_data = bytes.fromhex(clean_token)
            
            # 解密令牌数据
            decoded_meter_id, amount, transfer_counter, crc = \
                self.crypto.decrypt_token_data(encrypted_data)
            
            # 验证表计ID
            if str(decoded_meter_id) != meter_id:
                return False, None
            
            # 验证CRC
            token_data = self._build_token_data(meter_id, amount, transfer_counter)
            if not self.crypto.verify_crc(token_data, crc):
                return False, None
            
            # 返回令牌数据
            token_info = {
                'meter_id': meter_id,
                'amount': amount,
                'transfer_counter': transfer_counter,
                'crc': crc
            }
            
            return True, token_info
            
        except Exception as e:
            return False, None
    
    def _build_token_data(self, meter_id: str, amount: int, 
                         transfer_counter: int) -> bytes:
        """
        构建令牌数据
        
        Args:
            meter_id: 表计ID
            amount: 充值金额
            transfer_counter: 传输计数器
            
        Returns:
            令牌数据字节
        """
        meter_id_bytes = int(meter_id).to_bytes(4, 'big')
        amount_bytes = amount.to_bytes(3, 'big')
        transfer_counter_bytes = transfer_counter.to_bytes(2, 'big')
        
        return meter_id_bytes + amount_bytes + transfer_counter_bytes
    
    def parse_token(self, token: str) -> Optional[dict]:
        """
        解析令牌（不验证）
        
        Args:
            token: 令牌字符串
            
        Returns:
            令牌数据字典
        """
        try:
            # 清理令牌格式
            clean_token = token.replace(' ', '').replace('-', '')
            
            # 转换为字节
            encrypted_data = bytes.fromhex(clean_token)
            
            # 解密令牌数据
            meter_id, amount, transfer_counter, crc = \
                self.crypto.decrypt_token_data(encrypted_data)
            
            return {
                'meter_id': str(meter_id),
                'amount': amount,
                'transfer_counter': transfer_counter,
                'crc': crc
            }
            
        except Exception:
            return None
    
    def format_token(self, token_hex: str) -> str:
        """
        格式化令牌显示
        
        Args:
            token_hex: 十六进制令牌字符串
            
        Returns:
            格式化后的令牌字符串
        """
        clean_hex = token_hex.replace(' ', '').replace('-', '').upper()
        return ' '.join([clean_hex[i:i+4] for i in range(0, len(clean_hex), 4)])
    
    def validate_token_format(self, token: str) -> bool:
        """
        验证令牌格式
        
        Args:
            token: 令牌字符串
            
        Returns:
            格式是否有效
        """
        try:
            clean_token = token.replace(' ', '').replace('-', '')
            
            # 检查长度（DES加密后应该是8字节的倍数）
            if len(clean_token) % 16 != 0:
                return False
            
            # 检查是否为有效的十六进制
            bytes.fromhex(clean_token)
            
            return True
            
        except Exception:
            return False
